<template>
    <div>
      <div class="card" style="margin-bottom: 5px">
        <el-input v-model="data.name" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入宠物名称查询"></el-input>
        <el-button type="info" plain @click="load">查询</el-button>
        <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
      </div>

      <div class="card" style="margin-bottom: 5px">
        <el-table tooltip-effect="dark myTooltip" stripe :data="data.tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="宠物名称"></el-table-column>
          <el-table-column prop="typeName" label="宠物类型"></el-table-column>
          <el-table-column prop="sex" label="宠物性别"></el-table-column>
          <el-table-column prop="img" label="宠物图片">
            <template #default="scope">
              <el-image style="width: 50px; height: 50px; border-radius: 5px" :src="scope.row.img" :preview-src-list="[scope.row.img]" preview-teleported></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="introduce" label="宠物介绍" show-overflow-tooltip></el-table-column>
          <el-table-column label="宠物详情">
            <template #default="scope">
              <el-button type="primary" @click="view(scope.row.content)">查看内容</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right" align="center">
            <template v-slot="scope">
                <el-button type="primary" @click="handleFeed(scope.row)">喂养</el-button>
                <el-button type="warning" @click="handleManage(scope.row, '玩耍', 11)">玩耍</el-button>
                <el-button type="success" @click="handleManage(scope.row, '吃药', 10)">吃药</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card" v-if="data.total">
        <el-pagination @current-change="load" background layout="total, prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
      </div>
  
      <el-dialog :title="feedDiolag.title" v-model="feedDiolag.isShow" width="1000" destroy-on-close>
        <div style="margin: 20px 0" v-if="feedDiolag.goods.total > 0">
            <el-row :gutter="20">
                <el-col :span="6" v-for="item in feedDiolag.goods.list" :key="item.id">
                <div class="card cursor-pointer" style="padding: 0; border-radius: 5px; overflow: hidden; margin-bottom: 20px" >
                    <img :src="item.img" alt="" style="width: 100%; height: 200px">
                    <div style="padding: 10px">
                    <div style="font-size: 20px; margin-bottom: 10px; display: flex; align-items: center">
                        <el-tag type="success">售卖中</el-tag>
                        <span style="font-weight: bold; margin-left: 5px; flex: 1; width: 0" class="line1">{{ item.name }}</span>
                    </div>
                    <div style="display: flex; align-items: center; margin: 15px 0">
                        <div style="font-size: 18px; color: red; flex: 1">￥{{ item.price }}</div>
                    </div>
                    <div style="display: flex; align-items: center">
                        <div style="flex: 1">
                        <el-input-number v-model="item.num" :min="1" style="width: 100px" size="small"></el-input-number>
                        </div>
                        <div><el-button @click="addActionInfo(item)" type="danger" size="small">购买并使用</el-button></div>
                    </div>
                    </div>
                </div>
                </el-col>
            </el-row>
        </div>
        <div style="padding: 20px; text-align: center; color: #666" v-else>暂无商品信息...</div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="feedDiolag.isShow = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
  
      <el-dialog title="宠物详情" v-model="data.viewVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
        <div class="editor-content-view" style="padding: 20px" v-html="data.content"></div>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.viewVisible = false">关 闭</el-button>
      </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  
  import {reactive, ref} from "vue";
  import request from "@/utils/request.js";
  import {ElMessage, ElMessageBox} from "element-plus";
  import {Delete, Edit} from "@element-plus/icons-vue";
  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import {onBeforeUnmount, shallowRef} from "vue";
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  
  
  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    formVisible: false,
    form: {},
    tableData: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
    name: null,
    ids: [],
    shopList: [],
    typeList: [],
    rules: {
      name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
      ],
      typeId: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ],
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' }
      ]
    },
    viewVisible: false,
    content: null
  })
  
  const formRef = ref()
  
  const baseUrl = import.meta.env.VITE_BASE_URL

  const view = (content) => {
    data.content = content
    data.viewVisible = true
  }
  
  /* wangEditor5 初始化开始 */
  const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
  const mode = 'default'
  const editorConfig = { MENU_CONF: {} }
  // 图片上传配置
  editorConfig.MENU_CONF['uploadImage'] = {
    headers: {
      token: data.user.token,
    },
    server: baseUrl + '/files/wang/upload',  // 服务端图片上传接口
    fieldName: 'file'  // 服务端图片上传接口参数
  }
  // 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
  // 记录 editor 实例，重要！
  const handleCreated = (editor) => {
    editorRef.value = editor
  }
  /* wangEditor5 初始化结束 */
  
  request.get('/petShop/selectAll').then(res => {
    data.shopList = res.data
  })
  
  request.get('/petType/selectAll').then(res => {
    data.typeList = res.data
    let sellPet = JSON.parse(data.user.sellPet || '[]')
    // 筛选出当前的宠物店的 销售宠物类型的范围
    data.typeList = data.typeList.filter(type => sellPet.includes(type.name))
  })
  
  const load = () => {
    request.get('/pet/selectPage', {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name,
        typeId: 3
      }
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data?.list || []
        data.total = res.data?.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const handleSelectionChange = (rows) => {
    data.ids = rows.map(v => v.id)
  }
  
  const reset = () => {
    data.name = null
    load()
  }
  
  load()



  // 喂养管理
  const feedDiolag = reactive({
    isShow: false,
    title: '',
    pageNum: 1,
    pageSize: 10,
    goods: {
        total: 0,
        list: []
    },
    selectedPetName: ''
  })
  const handleFeed = async (row) => {
    await loadGoods(2)

    feedDiolag.selectedPetName = row.name
    feedDiolag.title = '喂养'
    feedDiolag.isShow = true
  }
  const handleManage = async (row, title, typeId) => {
    await loadGoods(typeId)
    
    feedDiolag.selectedPetName = row.name
    feedDiolag.title = title
    feedDiolag.isShow = true
  }
const loadGoods = (typeId) => {
  request.get('/goods/selectPage', {
    params: {
      pageNum: feedDiolag.pageNum,
      pageSize: feedDiolag.pageSize,
      typeId: typeId,
    }
  }).then(res => {
    if (res.code === '200') {
        feedDiolag.goods.list = res.data?.list || []
        feedDiolag.goods.total = res.data?.total
        feedDiolag.goods.list.forEach(item => item.num = 1)
    } else {
      ElMessage.error(res.msg)
    }
  })
}
loadGoods()

const addActionInfo = (goods) => {
    const data = {
        actionName: '使用了',
        goodsName: goods.name,
        goodsAccount: goods.num,
        petName: feedDiolag.selectedPetName
    }
    request.post('/petActionLog/add', data).then(res=>{
        if (res.code == 200) {
            ElMessage.success("操作成功")
        }else {
            ElMessage.error("系统异常")
        }
        feedDiolag.isShow = false
    })
} 

  </script>
  
  <style>
  .myTooltip {
    max-width: 40% !important;
  }
  </style>